package com.nefu.editor.service.Impl;

import com.nefu.editor.common.EdiException;
import com.nefu.editor.core.mapper.ArticleMapper;
import com.nefu.editor.core.mapper.CartMapper;
import com.nefu.editor.core.model.Article;
import com.nefu.editor.core.model.Cart;
import com.nefu.editor.core.model.User;
import com.nefu.editor.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenchenT
 * @date : 18-11-14
 * @since : java 8
 */
@Service
public class CartServiceImpl implements CartService {

    private final CartMapper cartMapper;
    private final ArticleMapper articleMapper;

    @Autowired
    public CartServiceImpl(CartMapper cartMapper, ArticleMapper articleMapper) {
        this.cartMapper = cartMapper;
        this.articleMapper = articleMapper;
    }

    @Override
    public List<Map<String, Object>> getCartByUserSystemId(User user) throws EdiException {
        List<Map<String, Object>> rtv=new ArrayList<>();
        if (null != user && null != user.getSystemId()) {
            List<Cart> carts = cartMapper.selectCartByUserSystemId(user);
            if (null != carts && 0 != carts.size()) {
                for (Cart cart : carts) {
                    Map<String, Object> map = new HashMap<>(4);
                    map.put("systemId", cart.getSystemId());

                    Article article = new Article();
                    article.setSystemId(cart.getArticleSystemId());
                    List<Article> articles = articleMapper.selectArticleByCondition(article);
                    if (null != articles && 1 == articles.size()) {
                        map.put("title", (articles.get(0)).getTitle());
                        map.put("image", (articles.get(0)).getImage());
                    }
                    map.put("sum", cart.getSum());
                    rtv.add(map);
                }
            } else {
                throw new EdiException("购物车空空如也!!");
            }
        } else {
            throw new EdiException("参数有误!");
        }
        return rtv;
    }
}
